<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Couplet;

class CoupletController extends Controller
{   

    private $couplet = array();
    private $user_id;
    public function __construct(){
        $couplets = Couplet::getCouplet();
        foreach($couplets as $couple){
            array_push($this->couplet,$couple->couplet_name);
        }
        $agent =  $_SERVER['HTTP_USER_AGENT'];
        parse_str($agent);
        if(!empty($register_id)){
            $this->user_id = $register_id;
            $phone = $this->getUserPhone($register_id);
            $this->insertUid($register_id,$phone);
        }
    }
    
    public function index(){
        return view('index',['u_id'=>$this->user_id]);
    }
    private function insertUid($user_id,$phone){
        Couplet::insertUid($user_id,$phone);
    }

    public function getUserId(Request $request){
        $phone = $request->input('phone');
        $code = $request->input('code');
        if(!empty($code)){
            $mobile = $request->session()->get('phone');
            $mobile_code = $request->session()->get('phone_code');
            if($mobile!=$phone){
                return response()->json([
                    'code'=>'202',
                    'msg'=>'手机号码不正确'
                ]);
            }
            if($mobile_code != $code){
                return response()->json([
                    'code'=>'202',
                    'msg'=>'手机验证码不正确'
                ]);
            }
        }
        $url = "https://act.hxsapp.com/outer/chineseYear/checkMobileIsReg";
        $data = array(
            'mobile'=>$phone,
            'utime'=>time(),
            'sign'=>base64_encode(md5(time().'c07MdQlFXvD7O!eE'))
        );
        $result = $this->curlPost($url,$data);
        $result = json_decode($result,true);
        if($result['data']['user_id']!=0){
            return response()->json([
                'code'=>'200',
                'msg'=>'接口调用成功',
                'data'=>$result['data']['user_id']
            ]);
        }else{
            return response()->json([
                'code'=>'201',
                'msg'=>'接口调用失败'
            ]);
        }
    }
    public function getUserPhone($user_id){
        $u_id = (int)$user_id;
        $url = "https://act.hxsapp.com/outer/chineseYear/getUserMobileByUserId";
        $data = array(
            'user_id'=>$u_id,
            'utime'=>time(),
            'sign'=>base64_encode(md5(time().'c07MdQlFXvD7O!eE'))
        );
        $result = $this->curlPost($url,$data);
        $result = json_decode($result,true);
        return $result['data']['mobile'];
    }
    private function curlPost($url,$post_data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    private function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
    public function show(Request $request){
        $share = $request->input('share');
        $user = $this->user_id;
        $is_share = false;
        // if(empty($user)){
        //     $user = $request->input('user_id');
        //     if(!$user){
        //         echo "<script>alert('请先登录')</script>";
        //         return redirect('/');
        //     }
        // }
        if(!empty($share)){
            $user = $request->input('user_id');
            $share_id = $request->input('share_id');
            $this->accept($share_id,$user);
            $is_share = true;
        }
        $couplets= $this->couplet;
        $this->getCouplet($user);
        $data = array(
            ['id'=>1,'name'=>$this->couplet[0],'status'=>0,'is_use'=>0],
            ['id'=>2,'name'=>$this->couplet[1],'status'=>0,'is_use'=>0],
            ['id'=>3,'name'=>$this->couplet[2],'status'=>0,'is_use'=>0],
            ['id'=>4,'name'=>$this->couplet[3],'status'=>0,'is_use'=>0],
            ['id'=>5,'name'=>$this->couplet[4],'status'=>0,'is_use'=>0],
            ['id'=>6,'name'=>$this->couplet[5],'status'=>0,'is_use'=>0],
            ['id'=>7,'name'=>$this->couplet[6],'status'=>0,'is_use'=>0],
            ['id'=>8,'name'=>$this->couplet[7],'status'=>0,'is_use'=>0],
            ['id'=>9,'name'=>$this->couplet[8],'status'=>0,'is_use'=>0],
            ['id'=>10,'name'=>$this->couplet[9],'status'=>0,'is_use'=>0]
        );
        $detail_array= array();
        $detail = Couplet::getUserCouplet($user);
        foreach($detail as $value){
            array_push($detail_array,array(
                'id'=>$value->id,
                'name'=>$value->couplet_name,
                'status'=>$value->couplet_status,
                'is_use'=>$value->is_use
            ));
        }  
        $finish = Couplet::finish($user)->finish;
        $num = Couplet::collect($user);
        $amount=0;
        foreach($num as $value1){
            $id = $value1->couplet_id;
            foreach($num as $value2){
                if($value2->couplet_id == $id+5){
                    $amount+=1;
                }
            }
        }
        $num = count($num);
        $finish_array= array(
            'status'=>$finish,
            'num'=>$num/10,
            'amount'=>$amount
        );

        // $id = Couplet::insert();
        return view('couplet',['data'=>$data,'detail'=>$detail_array,'finish'=>$finish_array,'u_id'=>$user,'share'=>$is_share]);
    }
    public function getUsedCouplet(Request $request){
        $user = $request->input('user');
        $isuse_array = array();
        $isuse = Couplet::getUserCoupletUsed($user);
        foreach($isuse as $value){
            array_push($isuse_array,array(
                'id'=>$value->couplet_id
            ));
        }
        return response()->json([
            'code'=>'200',
            'msg' => '已使用的对联',
            'data'=>$isuse_array
        ]);
    }
    public function getUserCoupletByid(Request $request){
        $user = $request->input('u_id');
        $couplet1 = $request->input('couplet1');
        $couplet2 = $request->input('couplet2');
        $detail = Couplet::getUserCoupletByid($user,$couplet1,$couplet2);
        $detail_array=array();
        foreach($detail as $value){
            array_push($detail_array,array(
                'id'=>$value->id,
                'name'=>$value->couplet_name,
                'status'=>$value->couplet_status,
                'is_use'=>$value->is_use
            ));
        }
        return response()->json([
            'code'=>'200',
            'msg' => '获取成功',
            'data'=>$detail_array
            ]);
    }
    public function getCouplet($u_id){
        //随机数
        $num = rand(0,100);
        //初始一定能中奖
        $num = 20;
        //用户id
        $user = $u_id;
        //判断用户是否已经参与了3个对联的活动
        $have_join = $this->checkUser($user);
        if($have_join){
            return response()->json([
            'code'=>'201',
            'msg' => '你已经参与了活动'
            ]);
        }else{
            //拿取3个对联
            $rand1 = $this->getRand();
            //检查rand2的值和rand1的值是否匹配
            $rand2 = $this->matchingCouplet($rand1,null,false);
            if($num<=30){
                //给30%的人匹配对红包
                $rand3 = $this->matchingCouplet($rand1,$rand2,true);
            }else{
                //另外的人没有红包
                $rand3 = $this->matchingCouplet($rand1,$rand2,false);
            }
            $couplet_array=array(
                $rand1,
                $rand2,
                $rand3
            );
            //更新用户活动，已参与活动
            Couplet::insertUserActivity($user);
            foreach($couplet_array as $value){
                //先自加1和数据库的id匹配上
                $value = $value+1;
                Couplet::insertUserCouplet($user,$value);
            }   
            return response()->json([
            'code'=>'200',
            'msg' => '恭喜领得3个对联'
            ]);
        }
    }
    //获取随机数组键值
    private function getRand(){
        return array_rand($this->couplet,1);
    }
    //匹配对联,$matching true表示匹配对对联，false表示不匹配对联
    private function matchingCouplet($num1=null,$num2=null,$matching){
        if($matching==true){
            if($num1<=4){
                $num3 = $num1+5;
            }else{
                $num3 = $num1-5;
            }
        }else{
            $num3 = $this->getRand();
            if($num3<=4){
                $checkNum = $num3+5;
                if($checkNum==$num1||$checkNum==$num2){
                    $res=$this->matchingCouplet($num1,$num2,$matching);
                    return $res;
                }
            }else{
                $checkNum = $num3-5;
                if($checkNum==$num1||$checkNum==$num2){
                    $res=$this->matchingCouplet($num1,$num2,$matching);
                    return $res;
                }
            }
        }
        return $num3;
    }
    //查看是否参与3个对联活动
    private function checkUser($user){
        return Couplet::getUserActivity($user);
    }
    //用户分享页面
    public function shareCouplet(){
        $user='123';
        $user_couplets = Couplet::getUserCouplet($user);
        $couplet_array=array();
        foreach($user_couplets as $value){
            array_push($couplet_array,array($value->id=>$value->couplet_name));
        }
        return view('shareCouplet',['couplets'=>$couplet_array]);
    }
    //用户分享操作
    public function userShareCouplet(Request $request){
        $give_user = $request->input('giveUser');
        $couplet_id = $request->input('couplet_id');
        //查看送对联的用户有无该对联
        $user_couplets = Couplet::getUserCouplet($give_user,$couplet_id);
        if(!empty($user_couplets)){
            //送春联
            Couplet::updataUserCouplet($give_user,$couplet_id);
            //增加一个分享春联的sql
            $id = Couplet::addShareCouplet($give_user,$couplet_id);
            return response()->json([
                'code'=>'200',
                'msg' => '赠送对联成功',
                'data'=>$id
            ]);
        }else{
            return response()->json([
                'code'=>'201',
                'msg' => '您没有该对联'
            ]);
        }
    }
    //接受对联页面
    public function acceptView(Request $request){
        $share_id = $request->input('share_id');
        return view('accept',['share_id'=>$share_id]);
    }
    //接受对联
    public function accept($share_id,$openid){
        $shareInfo = Couplet::getShareInfo($share_id);
        $user = $shareInfo->give_id;
        $couplet_id = $shareInfo->couplet_id;
        //查看user的是否分享
        if(!empty(Couplet::getUserShare($user,$couplet_id))){
            Couplet::insertUserCouplet($openid,$couplet_id);
            Couplet::updateUserShare($user,$couplet_id);
            return response()->json([
                'code'=>'200',
                'msg'=>'接口调用成功'
            ]);
        }else{
                return response()->json([
                'code'=>'202',
                'msg'=>'没有该对联'
            ]);
        }
    }
    //打开红包,赠送礼物
    public function openRed(Request $request){
        $user = $request->input('user');
        $couplet_id1 = $request->input('couplet_id1');
        $couplet_id2 = $request->input('couplet_id2');
        //查看送对联的用户有无该对联
        $user_couplets1 = Couplet::getUserCouplet($user,$couplet_id1);
        $user_couplets2 =  Couplet::getUserCouplet($user,$couplet_id2);
        //查看用户活动结束未
        $finish = Couplet::finish($user)->finish;
        if($finish!=0){
            return response()->json([
                'code'=> '201',
                'msg' => '你已经兑换大红包了'
            ]);
        }
        //查看用户是不是首次打开红包
        $first = Couplet::getFristPrize($user);
        if(empty($first)){
            $type=0;
        }else{
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) { 
                return response()->json([
                    'code'=>'201',
                    'msg'=>'请下载app，打开红包'
                ]);
            }
            $type=1;
        }
        //查看这对联是否已经兑换了红包
        $is_use = Couplet::getIsUseCouplet($user,$couplet_id1);
        if(!empty($is_use)){
            return response()->json([
                'code'=>'201',
                'msg'=>'你已打开过这个红包'
            ]);
        }
        if(!empty($user_couplets1)&&!empty($user_couplets2)){
            if($couplet_id1 +5 == $couplet_id2){
                //获取奖品
                $prize = $this->getPrize($type,$user);
                //写入用户奖品
                Couplet::insertUserPrize($user,$prize->id);
                //更新用户对联为已用
                Couplet::updateUseCouplet($user,$couplet_id1,$couplet_id2);
                Couplet::decrementPrize($prize->id);
                $prize = Couplet::getUserPrize($user);
                return response()->json([
                    'code'=>'200',
                    'msg'=>'打开成功',
                    'data'=>$prize
                ]);
            }else{
                return response()->json([
                    'code'=>'201',
                    'msg' => '打开失败'
                ]);
            }
        }else{
            return response()->json([
                'code'=>'201',
                'msg' => '没有对联，打开失败'
            ]);
        }

    }
    public function openBigRed(Request $request){
        $user = $request->input('u_id');
        //查看用户活动结束未
        $finish = Couplet::finish($user)->finish;
        if($finish!=0){
            return response()->json([
                'code'=>'201',
                'msg' => '你已经兑换大红包了'
            ]);
        }
        //查看用户是否集齐红包
        $collect = Couplet::collect($user);
        $type = 2;
        if($collect>=10){
            //获取奖品
            $prize = $this->getPrize($type,$user);
            //写入用户奖品
            Couplet::insertUserPrize($user,$prize);

            Couplet::updateAllPrize($user);
            $prize = Couplet::getUserPrize($user);
            return response()->json([
                'code'=>'200',
                'msg'=>'兑换成功',
                'data'=>$prize
            ]);
        }else{
            return response()->json([
                'code'=>'201',
                'msg' => '没集齐，请集齐再来'
            ]);
        }
    }
    //通过概率获取奖品
    private function getPrize($type,$user){
        $prizes=Couplet::getPrize($type);
        $prize_array = array();
        $accept_probability = 0;
        $probability_array =array();
        $sum_probability = 0;
        foreach($prizes as $prize){
            $sum_probability+= intval($prize->prize_probability);
            array_push($probability_array,array(
                'probability'=>$sum_probability,
                'id'=>$prize->id
            ));
        }
        $rand = rand(0,$sum_probability);
        $probability_key = null;
        foreach($probability_array as $key => $value){
            if(($key-1) < 0){
                $probability1=0;
                $probability2=$probability_array[$key]['probability'];
            }else{
                $probability1=$probability_array[$key-1]['probability'];
                $probability2=$probability_array[$key]['probability'];
            }
            if($probability1<=$rand&&$rand<$probability2){
                $probability_key =  $probability_array[$key]['id'];
            }
        }
        $quantity = Couplet::getQuantity($probability_key);
        $quantity = $quantity->quantity;
        if($quantity<=0){
            $this->getPrize($type,$user);
        }
        $prize = Couplet::getPrize($type,$probability_key);
        return $prize[0];
    }
    //我的奖品
    public function myPrize(Request $request){
        $user = $this->user_id;
        if(empty($user)){
            $user = $request->input('u_id');
            if(!$user){
                echo "<script>alert('请先登录')</script>";
                return redirect('/');
            }
        }
        $myPrize  = Couplet::getMyPrize($user);
        $myPrize_array = array();
        $amount = 0;
        foreach($myPrize as $value){
            array_push($myPrize_array,array(
                'id'=>$value->prize_id,
                'name'=>$value->prize_name,
                'status'=>$value->status,
                'add_time'=>date('Y-m-d',$value->add_time),
                'amount'=>$value->amount,
                'prize_type'=>$value->prize_type
            ));
            if($value->status == 0){
                $amount +=$value->amount;
            }
        }
        return view('myPrize',['prize'=>$myPrize_array,'amount'=>$amount,'u_id'=>$user]);
    }
    //后台配置奖品
    public function setPrize(){
        $type=0;
        $prizes = Couplet::getPrize($type);
        $prize_array = array();
        foreach($prizes as $prize){
            array_push($prize_array,array(
                'id'=>$prize->id,
                'prize_name'=>$prize->prize_name,
                'prize_probability'=>$prize->prize_probability
            ));
        }
        return view('setPrize',['prizes'=>$prize_array]);
    }
    //通过id获取奖品
    public function getPrizeByid(Request $request){
        $type =$request->input('type');
        $prize_id = $request->input('prize_id');
        $prizes = Couplet::getPrize($type,$prize_id);
        $prize_array = array();
        foreach($prizes as $prize){
            array_push($prize_array,array(
                'id'=>$prize->id,
                'prize_name'=>$prize->prize_name,
                'prize_probability'=>$prize->prize_probability,
                'amount'=>$prize->amount,
                'prize_type'=>$prize->prize_type
            ));
        }
        return response()->json([
                'code'=>'200',
                'msg' => '获取成功',
                'data'=>$prize_array
        ]);
    }
    public function getPrizeBytype(Request $request){
        $type = $request->input('type');
        $prizes = Couplet::getPrizeBytype($type);
        $prize_array= array();
        foreach($prizes as $prize){
            array_push($prize_array,array(
                'id'=>$prize->id,
                'prize_name'=>$prize->prize_name
            ));
        }
        return response()->json([
                'code'=>'200',
                'msg' => '获取成功',
                'data'=>$prize_array
        ]);
    }
    //后台 添加奖品
    public function addPrize(Request $request){
        $prize_name = $request->input('prize_name');
        $prize_probability = $request->input('prize_probability');
        $type = $request->input('type');
        $amount = $request->input('amount');
        $prize_type = $request->input('prize_type');
        $quantity = $request->input('quantity');
        $res = Couplet::addPrize($type,$prize_name,$prize_probability,$amount,$prize_type,$quantity);
        if($res){
            return redirect('setPrize')->with('status','success');
        }else{
            return redirect('setPrize')-with('status','error');
        }
    }
    //后台 更新奖品
    public function updatePrize(Request $request){
        $prize_id = $request->input('prize_id');
        $prize_name = $request->input('prize_name');
        $prize_probability = $request->input('prize_probability');
        $type = $request->input('type');
        $amount = $request->input('amount');
        $prize_type = $request->input('prize_type');
        $quantity = $request->input('quantity');
        $res = Couplet::updatePrize($type,$prize_id,$prize_name,$prize_probability,$amount,$prize_type,$quantity);

        if($res){
            return redirect('setPrize')->with('status','success');
        }else{
            return redirect('setPrize')->with('status','error');
        }
    }
    //微信授权，点亮页面
    public function wx(Request $request){
        $help_id = $request->input('help_id');
        $appid='wxd209fec05cc4b1d1';
        $redirect_uri = urlencode ( 'http://hxsh5.fsgit.cn/help?help_id='.$help_id);
        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        return redirect($url);
    }
    //点亮活动
    public function help(Request $request){
        $openid = $this->getUserInfo();
        $help_id = $request->input('help_id');
        if($openid==false){
           return redirect('/wx?help_id='.$help_id);
        }
        $user_help = $this->getUserHelp($help_id);
        $other_array=array();
        $amount = 0;
        foreach($user_help as $value){
            $amount += $value->num;
            $detail_array=array(
                'id'=>$value->id,
                'user'=>$value->u_id,
                'couplet_id'=>$value->couplet_id,
                'couplet_name'=>$value->couplet_name,
                'status'=>$value->status
            );
            array_push($other_array,array(
                'other_id'=>$value->other_id,
                'other_num'=>$value->num,
                'other_time'=>date('Y:m:d',$value->add_time),
                'img'=>$value->img,
                'name'=>$value->name
            )); 
        }
        $detail_array['other']=$other_array;
        $men=Couplet::countOther($help_id);
        return view('help',['detail'=>$detail_array,'amount'=>$amount,'openid'=>$openid,'count'=>$men]);
    }
    private function getUserInfo(){
        $appid = "wxd209fec05cc4b1d1";  
        $secret = "846108cefb23564f7ebb3c95c1f8d250";  
        $code = $_GET["code"];
        //第一步:取全局access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $token = $this->getJson($url);
        
        //第二步:取得openid
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $oauth2 = $this->getJson($oauth2Url);
        if(!empty($oauth2['errcode'])){
                return false;
        }
        //第三步:根据全局access_token和openid查询用户信息  
        $access_token = $token["access_token"];  
        $openid = $oauth2['openid'];  
        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $userinfo = $this->getJson($get_user_info_url);
        
        $img = $userinfo['headimgurl'];
        $nickname = $userinfo['nickname'];
        $openid = $userinfo['openid'];
        Couplet::insertOpenId($openid,$img,$nickname);
        return $openid;
    }
    //获取用户助力活动详细
    private function getUserHelp($help_id){
        $helps = Couplet::getPeople($help_id);
        return $helps;
    }
    //用户开始助力活动
    public function strat_help (Request $request){
        $user = $request->input('u_id');
        $couplet_id = $request->input('couplet_id');
        //先查询用户是否有活动参加
        $user_help = Couplet::checkUserHelp($user,$couplet_id);
        if(!$user_help){
            $res = Couplet::insert_help($user,$couplet_id);
            if($res){
                return response()->json([
                    'code'=>'200',
                    'msg' => '参加成功',
                    'data'=>$res
                ]);
            }else{
                return response()->json([
                    'code'=>'201',
                    'msg' => '分享活动只能参加两次',
                ]);
            }
        }else{
            return response()->json([
                'code'=>'201',
                'msg' => '你已经参加过了',
            ]);
        }
    }
    //其它人点击助力活动
    public function help_action(Request $request){
        $help_id = $request->input('help_id');
        $openid = $request->input('openid');
        $user = $request->input('u_id');
        $couplet_id = $request->input('couplet_id');
        $num = rand(10,30);
        //查看活动结束了没
        $finish = Couplet::get_help_finish($user,$couplet_id,$help_id);
        if($finish){
            $join = $this->getJoin($openid,$help_id,0);
            if($join==0){    
                $res = Couplet::other_help($user,$openid,$couplet_id,$help_id,$num);
                if($res){
                    return response()->json([
                        'code'=>'200',
                        'msg' => '点亮成功',
                    ]);
                }else{
                    return response()->json([
                        'code'=>'201',
                        'msg' => '点亮失败',
                    ]);
                }
            }else{
                return response()->json([
                    'code'=>'201',
                    'msg' => '您已经点亮过了',
                ]);
            }
        }else{
            return response()->json([
                'code'=>'201',
                'msg' => '点亮活动已完成',
            ]);
        }
    }
    //获取用户点亮了没
    private function getJoin($openid,$help_id,$status=null){
        return Couplet::getJoin($openid,$help_id,$status);
    }

    public function getHelpById(Request $request){
        $help_id = $request->input('help_id');
        $openid = $request->input('openid');
        $status = $this->getJoin($openid,$help_id);
        if($status>0){
            return response()->json([
                'code'=>'201',
                'msg' => '已经帮忙点亮',
            ]);
        }else{
            return response()->json([
                'code'=>'200',
                'msg' => '没有帮忙点亮',
            ]);
        }
    }

    private function Post($curlPost,$url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }
    
    //将 xml数据转换为数组格式。
    private function xml_to_array($xml){
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if(preg_match_all($reg, $xml, $matches)){
            $count = count($matches[0]);
            for($i = 0; $i < $count; $i++){
            $subxml= $matches[2][$i];
            $key = $matches[1][$i];
                if(preg_match( $reg, $subxml )){
                    $arr[$key] = $this->xml_to_array( $subxml );
                }else{
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }
    
    //random() 函数返回随机整数。
    private function random($length = 6 , $numeric = 0) {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
    public function sendCode(Request $request){
        //短信接口地址
        $target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
        //获取手机号
        $mobile = $request->input('phone');
        //生成的随机数
        $mobile_code = $this->random(4,1);
        if(empty($mobile)){
            return response()->json([
                'code'=>'201',
                'msg' => '手机号码不能为空',
            ]);
        }
        $post_data = "account=C83369032&password=a52285b77be623c7e012aa4efa04b539&mobile=".$mobile."&content=".rawurlencode("您的验证码是：".$mobile_code."。请不要把验证码泄露给其他人。");
        //用户名是登录ihuyi.com账号名（例如：cf_demo123）
        //查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
        $xml = $this->Post($post_data, $target);
        $gets =  $this->xml_to_array($xml);
        if($gets['SubmitResult']['code']==2){
            $request->session()->put('phone',$mobile);
            $request->session()->put('phone_code',$mobile_code);
            return response()->json([
                'code'=>'200',
                'msg' => '成功获取验证码',
            ]);
        }
        return response()->json([
            'code'=>'201',
            'msg' => '获取验证码失败',
        ]);
    }
}
